|
|
|
|
|
|
|
If using public variables can cause problems in the application, why should they be used? In most cases, you should use public variables in the following situations: |
|
|
|
|
|
|
|
|
When you must access information anywhere in your application (such as custom color and font information) |
|
|
|
|
|
|
|
|
When you are creating constants to be used in your application (note that constants cannot be declared as private) |
|
|
|
|
|
|
|
|
To allow access to a database workspace without opening multiple instances of the database |
|
|
|
|
|
|
|
|
When you must access Windows API calls in the application |
|
|
|
|
|
|
|
|
Tip If you must use any public variables, you should declare them in a standard module rather than in one of the form modules in the application. This gives you a centralized location for all of these variables. That way you would not accidentally declare another public variable with the same name. |
|
|
|
|
|
|
|
|
|
Watching Out for Problems |
|
|
|
|
|
|
|
|
The more public a variable becomes, the more cluttered your programs become and the easier it is for bugs to enter the picture. Despite the fact that public variables sound useful, you do not want to use them unless doing so is absolutely necessary. Typically, only a few procedures must share the same data values; most procedures don't need to share data at all. |
|
|
|
|
|
|
|
|
One of the most common mistakes a programmer can make is to use the same variable name in multiple places for different reasons. If that variable is explicitly declared as a private variable in the different routines, then except for the issue of duplicate names from a documentation perspective, no harm is done. However, if that variable is declared as a module-level variable or as a public variable, you would wind up changing the value in the variable that might still be used in another routine in the application. This causes one of the hardest types of bugs to find and fix. |
|
|
|
|
|
|
|
|
You have seen that variables can be either local (private) or global (public), and that routines often must share data among themselves. However, you now know that when you declare public variables you open yourself up to problems that could occur by reusing variable names. An overwhelming problem is that you must share data between procedures but you've been told that you shouldn't include module-level and public variables in your applications. The way around this dilemma is to pass the data that a procedure needs directly to that procedure. |
|
|
|
|
|